<template>
  <el-dialog :model-value="show" width="30%" title="分配角色" @closed="emit('close')">
    <el-select v-model="userRoles" multiple>
      <el-option v-for="item in allRoleList" :key="item.id" :value="item.id" :label="item.name" />
    </el-select>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="emit('close')">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang='ts'>
import { getAllRoleListApi, getUserRoleListApi, allocUserRoleApi } from '@/api'
import { ElMessage, ElMessageBox } from 'element-plus';
import { ref, watch } from 'vue';
const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  roleId: {
    type: Number,
    default: 0
  }
})

const emit = defineEmits(['close']);

const userRoles = ref<number[]>([])
const allRoleList = ref<IRoleModel[]>([])

getAllRoleListApi().then(res => {
  if (res.code === 200) {
    allRoleList.value = res.data;
  }
})

watch(() => props.roleId, (val) => {
  if (props.roleId !== 0) {
    getUserRoleListApi(props.roleId).then(res => {
      if (res.code === 200) {
        userRoles.value = res.data.map(item => item.id);
      }
    })
  }
})

const submit = () => {
  ElMessageBox.confirm('确定要分配角色吗?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
    allocUserRoleApi({
      adminId: props.roleId,
      roleIds: userRoles.value
    }).then(res => {
      if (res.code === 200) {
        ElMessage.success('分配成功');
        emit('close');
      }
    })
  })
}

</script>
<style lang="less" scoped></style>